const Koa = require("koa");
const http = require("http"); // 引入 HTTP 模块
const WebSocket = require("ws"); // 引入 WebSocket 模块
const bodyparser = require("koa-bodyparser");
const cors = require("koa-cors");
const static = require("koa-static");
const path = require("path");
const router = require("./routes/index");
const koaBody = require('koa-body').koaBody;
const config = require("./config");
const fs = require("fs");
const convertPcmToText = require("./routes/services/getbaiduVoiceService");
const { BAIDU_CLIENT_ID, BAIDU_CLIENT_SECRET } = require("./config");
// 创建 Koa 实例
const app = new Koa();

// 创建 HTTP 服务器，并将 Koa 应用传入
const server = http.createServer(app.callback());

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ noServer: true });

// 当 WebSocket 连接建立时触发
wss.on("connection", (socket, req) => {
  console.log("New client connected");
  let pcmBuffer = Buffer.alloc(0);
  // 监听客户端消息
  // 监听原始数据帧
  let flag = 0;
  socket._socket.on("data", (chunk) => {
    const firstByte = chunk[0]; // 数据帧的第一个字节
    const fin = (firstByte & 0x80) === 0x80; // FIN 位
    const opcode = firstByte & 0x0f; // Opcode 位
    console.log(`监听原始数据帧start-FIN: ${fin}, Opcode: ${opcode}`);

    // 根据操作码处理
    switch (opcode) {
      case 0x1:
        flag++;
        if(flag == 2){
          flag=0;
          console.log('读取pcm流完毕')
          convertPcmToText(pcmBuffer);
          pcmBuffer = Buffer.alloc(0);
        }
        break;
      case 0x2:
        if (flag == 1) {
          //开始读取pcm流
          pcmBuffer = Buffer.concat([pcmBuffer, chunk]); // 拼接接收到的 PCM 数据
          console.log("pcmBuffer", pcmBuffer);
        }
        console.log("监听原始数据帧 Binary frame received");
        break;
      case 0x8:
        console.log(" 监听原始数据帧 Connection close frame received");
        break;
      case 0x9:
        console.log("监听原始数据帧 Ping frame received");
        break;
      case 0xa:
        console.log(" 监听原始数据帧 Pong frame received");
        break;
      default:
        console.log("监听原始数据帧 Unknown frame received");
    }
  });
  // 向客户端发送消息
  // ws.send("Hello, you are connected to the WebSocket server!");
});

//-------------------------------------------
const VoiceTokenService = require("./routes/services/baiduVoiceService");

(async () => {
  const clientId = BAIDU_CLIENT_ID;
  const clientSecret = BAIDU_CLIENT_SECRET;

  const voiceTokenService = new VoiceTokenService(clientId, clientSecret);

  try {
    const voiceToken = await voiceTokenService.getVoiceToken();
    console.log("Voice Token:", voiceToken);

    // 使用语音 Token 调用其他百度接口
  } catch (error) {
    console.error("Error fetching voice token:", error.message);
  }
})();

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    console.log(ctx.request.url);
    if (
      ctx.request.url === "/api/v1/user/reg" ||
      ctx.request.url === "/api/v1/user/login"
    ) {
      await next();
    } else {
      ctx.body = {
        code: 500,
        msg: "啥意思",
      };
    }
  } catch (e) {
    console.log(`server err: ${e}`);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      msg: "server error!",
    };
  }
});

app.use(
  koaBody({
    // 支持文件格式
    multipart: true,
    formidable: {
      // 上传目录
      uploadDir: path.join(__dirname, "public"),
      // 保留文件扩展名
      keepExtensions: true,
    },
  })
);

// 解析post请求请求体
app.use(bodyparser());

// 后端跨域
app.use(cors());

// 设置静态资源
app.use(static(path.join(__dirname, "public")));

// 启用路由
app.use(router.routes(), router.allowedMethods());

// 监听 HTTP 请求的升级（Upgrade）请求，允许 WebSocket 连接
server.on("upgrade", (req, socket, head) => {
  if (req.headers["upgrade"] === "websocket") {
    wss.handleUpgrade(req, socket, head, (ws) => {
      wss.emit("connection", ws, req);
    });
  }
});

// 启动 HTTP 服务器，监听端口
server.listen(config.port, () => {
  console.log(`Server is running on ${config.baseURL}:${config.port}`);
});
